import appinfo from '@/app.conf.js'

const url = (path) => {
  if (process.env.NODE_ENV === 'development') {
    // #ifdef H5
    return 'http://localhost:8080/' + (path.charAt(0) === '/' ? path.slice(1) : path)
    // #endif
    // #ifndef H5
    return appinfo.siteroot + '/' + (path.charAt(0) === '/' ? path.slice(1) : path)
    // #endif
  } else if (process.env.NODE_ENV === 'production') {
    return appinfo.siteroot + '/' + (path.charAt(0) === '/' ? path.slice(1) : path)
  }
}

export function openapi_url(path) {
  return path
}

const asset = (url) => {
  if (url !== undefined && url !== null) {
    if (isUrl(url)) {
      return url;
    } else {
      let href = window.location.href
      return (new URL(href)).origin + '/' + url
    }
  } else {
    return ''
  }
}

const isUrl = (str_url) => {
  var strRegex = '^http[s]?:\\/\\/([\\w-]+\\.)+[\\w-]+([\\w-./?%&=]*)?$';
  var re = new RegExp(strRegex);
  return re.test(str_url);
}

const replaceImg = (rich_text) => {
  var b = /<img [^>]*src=['"]([^'"]+)[^>]*>/g;// img 标签取src里面内容的正则
  var s = rich_text.match(b);// 取到所有img标签 放到数组 s里面
  if (s !== null && s !== undefined && s.length > 0) {
    for (var i = 0; i < s.length; i++) {
      var srcImg = s[i].replace(b, '$1');//取src面的内容
      if (srcImg.slice(0, 4) == 'http' || srcImg.slice(0, 5) == 'https') {
        //若src前4位置或者前5位是http、https则不做任何修改
        // console.log('不做任何修改');
      } else {
        //修改富文本字符串内容 img标签src 相对路径改为绝对路径
        rich_text = rich_text.replace(new RegExp(srcImg, 'g'), appinfo.siteroot + '/' + (srcImg.charAt(0) === '/' ? srcImg.slice(1) : srcImg)); //'http://www.dlzjzx.tj.cn'自己替换的内容
      }
    }
    rich_text = rich_text.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ')
  }
  return rich_text
}

module.exports.url = url
module.exports.asset = asset
module.exports.isUrl = isUrl
module.exports.replaceImg = replaceImg